package com.huaifang.yan.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

public class NioBootStart {

    public static void main(String[] args) {
        try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {

            serverSocketChannel.bind(new InetSocketAddress(9999));
            serverSocketChannel.configureBlocking(false);
            List<SocketChannel> list = new ArrayList<>();
            System.out.println("服务端启动开始监听.....");
            while (true) {

                ByteBuffer byteBuffer = ByteBuffer.allocate(20);
                SocketChannel channel = serverSocketChannel.accept();
                if (channel != null) {
                    System.out.println("有人来了.....");
                    channel.configureBlocking(false);
                    list.add(channel);
                }
                for (SocketChannel socketChannel : list) {
                    if (socketChannel.isOpen()) {
                        try {
                            int size = socketChannel.read(byteBuffer);
                            if (size > 0) {
                                byteBuffer.flip();
                                byte[] bytes = new byte[byteBuffer.limit()];
                                byteBuffer.get(bytes);
                                System.out.println(new String(bytes));
                                byteBuffer.clear();
                            }

                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        System.out.println("有人走了.....");
                    }
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
